package com.vpen.springsecuritytest.handler;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * -@Version 1.0
 * -@Author:Vpen
 * -@Date:2021/3/14 14:52
 * -@Content:自定义成功后的处理器，转发或者重定向自己代码实现
 */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler{
    private String url;
    private Boolean isRedirect;

    public MyAuthenticationSuccessHandler(String url, Boolean isRedirect) {
        this.url = url;
        this.isRedirect = isRedirect;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Boolean getRedirect() {
        return isRedirect;
    }

    public void setRedirect(Boolean redirect) {
        isRedirect = redirect;
    }

    /**
    * -@author Vpen
    * -@name onAuthenticationSuccess
    * -@date 2021/3/14 14:57
    * -@param
     * [request,请求对象，转发，request.getRequestDispatch(path).forward()
     * response,响应对象，重定向，response.sendRedirect(path)
     * authentication，用户登录成功的对象，内容是用户名和用户权限，内容由UserDetailsService返回的User
     * ]
    * -@return void
    * -@作用:
    */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
    if (null==url) return ;

    if (isRedirect){
        // 重定向
        response.sendRedirect(url);
    }else {
        // 转发
        request.getRequestDispatcher(url).forward(request,response);
    }
    }

}
